﻿using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.Process;
using ProduceBasicData.Domain.FactoryModeling;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.Process
{
    /// <summary>
    /// 工序维护信息更新处理类
    /// </summary>
    public class UpdateProcessHandler : IRequestHandler<UpdateProcessCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<ProcessModel> processRepo;
        private readonly IMapper mapper;

        public UpdateProcessHandler(IBaseRespository<ProcessModel> processRepo,
            IMapper mapper)
        {
            this.processRepo = processRepo;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(UpdateProcessCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res=new ApiResult<int>();

            var process = await processRepo.GetModelAsync(request.Id);
            if (process == null)
            {
                res.Code = ApiEnum.Failed;
                res.Msg = "您要修改的数据不存在";
                return res;
            }
            var model=mapper.Map(request, process);
            model.UpdateTime = DateTime.Now;
            model.UpdateName=request.UpdateName;

            var r=await processRepo.Update(model);
            if (r>0)
            {
                res.Data= r;
                res.Code = ApiEnum.Success;
                res.Msg = "工序维护信息更新成功";
            }
            else
            {
                res.Code = ApiEnum.Failed;
                res.Msg = "工序维护信息更新失败";
            }
            return res;
        }
    }
}
